<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.bomName" clearable :placeholder="$t('bom.bomName')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.bomCode" clearable :placeholder="$t('bom.bomCode')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable="" style="width: 350px" @change="handleFilter">
        <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
      <el-button
        v-if="editRight"
        v-waves
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        @click="handleDownloadBom"
      >
        {{ $t('bom.downloadBom') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-style="{height:'20px'}"
      :cell-style="{padding:'2px'}"
      @sort-change="sortChange"
    >
      <el-table-column :label="$t('bom.bomCode')" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.bomName')" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.bomVer')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomSetVersion }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.picNumberVer')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.matVer }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.partGrp')" width="130px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.partGrp }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.bomCode')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bomSetId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.altMatFlag')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.altMatFlag }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('order.number')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.matQty }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.serialInputFlag')" width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.serialInputFlag }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.serialType')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.serialType }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.processNumber')" width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('processing.processingNumber')" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processingNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('processing.processingVer')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processingVer }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('bom.seqNum')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.seqNum }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="160px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="130px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('bom.bomCode')" required prop="bomCode">
          <el-input v-model="temp.bomCode" clearable />
        </el-form-item>
        <el-form-item :label="$t('bom.bomName')" required prop="bomName">
          <el-input v-model="temp.bomName" />
        </el-form-item>
        <el-form-item :label="$t('order.bomVer')" required prop="bomSetVersion">
          <el-input v-model="temp.bomSetVersion" />
        </el-form-item>
        <el-form-item :label="$t('order.picNumberVer')" required prop="matVer">
          <el-input v-model="temp.matVer" />
        </el-form-item>
        <el-form-item :label="$t('bom.partGrp')" required prop="partGrp">
          <el-input v-model="temp.partGrp" />
        </el-form-item>
        <el-form-item :label="$t('order.bomCode')" required prop="bomSetId">
          <el-input v-model="temp.bomSetId" />
        </el-form-item>
        <el-form-item :label="$t('bom.altMatFlag')" required prop="altMatFlag">
          <el-input v-model="temp.altMatFlag" />
        </el-form-item>
        <el-form-item :label="$t('order.number')" required prop="matQty">
          <el-input v-model="temp.matQty" />
        </el-form-item>
        <el-form-item :label="$t('bom.serialInputFlag')" required prop="serialInputFlag">
          <el-input v-model="temp.serialInputFlag" />
        </el-form-item>
        <el-form-item :label="$t('bom.serialType')" required prop="serialType">
          <el-input v-model="temp.serialType" />
        </el-form-item>
        <el-form-item :label="$t('equipment.processNumber')" required prop="processNumber">
          <el-select v-model="temp.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable="" style="width: 450px">
            <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('processing.processingVer')" required prop="processingVer">
          <el-input v-model="temp.processingVer" />
        </el-form-item>
        <el-form-item :label="$t('bom.seqNum')" required prop="seqNum">
          <el-input v-model="temp.seqNum" />
        </el-form-item>
        <el-form-item :label="$t('processing.processingNumber')" required prop="processingNumber">
          <el-input v-model="temp.processingNumber" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 点击下载弹窗 -->
    <el-dialog :title="$t('bom.downloadBom')" :visible.sync="dialogForm" class="diag">
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="orderList"
        :header-row-style="{color: 'black'}"
        :header-cell-style="{background: 'lightBlue'}"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column :label="$t('order.orderCode')" width="auto" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="downloadList(row.orderCode)">{{ row.orderCode }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('order.orderName')" width="auto" align="center">
          <template slot-scope="{row}">
            <span>{{ row.orderName }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { getBomList, creatBom, updateBom, deleteBom, downloadBomList } from '@/api/bom'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'
import { getOrderList } from '@/api/order'
import { getProcessList } from '@/api/equipment'

export default {
  name: 'BomDefinition',
  components: {
    Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      total: 0,
      processOptions: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        bomCode: '',
        lineNumber: this.$store.getters.lineNumber,
        processNumber: '',
        bomName: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+due_date'
      },
      orderListQuery: {
        page: 1,
        limit: 20,
        state: 0,
        orderCode: '',
        lineNumber: '',
        typeNo: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+due_date'
      },
      showReviewer: false,
      temp: {
        bomId: 0,
        bomCode: '',
        bomName: '',
        bomSetVersion: '',
        matVer: 0,
        partGrp: '',
        bomSetId: '',
        altMatFlag: '',
        matQty: 0,
        serialInputFlag: '',
        serialType: '',
        processNumber: '',
        processingVer: '',
        seqNum: 0,
        processingNumber: ''
      },
      orderList: [],
      dialogFormVisible: false,
      dialogForm: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        bomCode: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        bomSetVersion: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        matVer: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        partGrp: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        bomSetId: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        bomaltMatFlagCode: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        matQty: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        serialInputFlag: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        serialType: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processingVer: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        seqNum: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processingNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        bomName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false,
      searchLoading: {
        company: false,
        manager: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        company: false,
        manager: false
      }
    }
  },
  created() {
    this.getList()
    this.getOrder()
    this.getProcessOptions()
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.orderListQuery.lineNumber = this.$store.getters.lineNumber
  },
  methods: {
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 获取订单号清单
    getOrder() {
      this.listLoading = true
      getOrderList(this.orderListQuery).then(response => {
        // console.log(response)
        response.data.orders.forEach(e => {
          var newObj = {}
          newObj['orderCode'] = e.orderCode
          newObj['orderName'] = e.orderName
          this.orderList.push(newObj)
        })
        // console.log(this.orderList)
        this.listLoading = false
      })
    },
    // 获取工艺流程选项
    getProcessOptions() {
      this.listLoading = true
      this.processOptions = []
      getProcessList(this.listQuery).then(response => {
        this.processOptions = response.data.processes
        this.listLoading = false
      })
    },
    // 下载bom动作
    downloadList(data) {
      this.orderListQuery.orderCode = data
      this.$confirm(i18n.t('produce.downloadOrNot'), i18n.t('common.tip'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        downloadBomList(this.orderListQuery).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: i18n.t('msg.DOWNLOAD_SUCCESS')
          })
          this.listLoading = false
        })
      })
    },
    // 获取清单
    getList() {
      // this.listLoading = false
      this.listLoading = true
      getBomList(this.listQuery).then(response => {
        this.list = response.data.boms
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 查看线体设备
    handleCheckLine(row) {
      const ret = Object.assign({}, row) // copy obj
      this.$router.push({ path: '/equipment/stationDef', query: { lineId: ret.lineId }})
    },
    // 查看错误信息
    handleCheck(row) {
      const ret = Object.assign({}, row) // copy obj
      if (ret.errMsg === null | '') {
        return
      }
      this.$msgbox({
        message: ret.errMsg,
        type: 'error'
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'startDate') {
        this.sortByCreatTime(order)
      } else if (prop === 'dueDate') {
        this.sortBydueDate(order)
      } else if (prop === 'priority') {
        this.sortByPriority(order)
      }
    },
    // 根据创建时间排序
    sortByCreatTime(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+start_date'
      } else {
        this.listQuery.sort = '-start_date'
      }
      this.handleFilter()
    },
    // 根据交期排序
    sortBydueDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+due_date'
      } else {
        this.listQuery.sort = '-due_date'
      }
      this.handleFilter()
    },
    // 根据优先级
    sortByPriority(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+priority'
      } else {
        this.listQuery.sort = '-priority'
      }
      this.handleFilter()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        bomId: 0,
        bomCode: '',
        bomName: '',
        bomSetVersion: '',
        matVer: 0,
        partGrp: '',
        bomSetId: '',
        altMatFlag: '',
        matQty: 0,
        serialInputFlag: '',
        serialType: '',
        processNumber: '',
        processingVer: '',
        seqNum: 0,
        processingNumber: ''
      }
    },
    // 新建一条线体
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatBom(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 下载物料清单
    handleDownloadBom() {
      this.dialogForm = true
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateBom(this.temp).then(response => {
            const index = this.list.findIndex(v => v.bomId === this.temp.bomId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteBom(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('bom.bomCode'),
          i18n.t('bom.bomName'),
          i18n.t('order.bomVer'),
          i18n.t('order.picNumberVer'),
          i18n.t('bom.partGrp'),
          i18n.t('order.bomCode'),
          i18n.t('bom.altMatFlag'),
          i18n.t('order.number'),
          i18n.t('bom.serialInputFlag'),
          i18n.t('bom.serialType'),
          i18n.t('equipment.processNumber'),
          i18n.t('processing.processingVer'),
          i18n.t('bom.seqNum'),
          i18n.t('processing.processingNumber')
        ]
        const filterVal = [
          'bomCode',
          'bomName',
          'bomSetVersion',
          'matVer',
          'partGrp',
          'bomSetId',
          'altMatFlag',
          'matQty',
          'serialInputFlag',
          'serialType',
          'processNumber',
          'processingVer',
          'seqNum',
          'processingNumber'
        ]
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '物料清单' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.diag{
   .el-dialog{
  width: 40%;
}
}
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
